class Solution {
public:
    vector<int> father,size;
    int find(int x){
        if(x != father[x]){
            father[x] = find(father[x]);
        }
        return father[x];
    }
    void Union(int u,int v){
        int x = find(u);
        int y = find(v);
        if(x == y) return;
        father[y] = x;
        size[x] += size[y];
    }
    int countServers(vector<vector<int>>& grid) {
        int m = grid.size();
        int n = grid[0].size();
        father.resize(m+n);
        size.resize(m+n,1);
        
        for(int i = 0;i < m+n;i++){
            father[i] = i;
        }
      
        int num = 0;
        for(int i = 0;i < m;i++){
            for(int j = 0;j < n;j++){
                if(grid[i][j] == 1){
                    Union(i,j+m);
                    num++;
                }
            }
        }
        
        int ret = 0;
        for(int i = 0;i < m+n;i++){
            if(father[i] == i && size[i] == 2){
                ret++;
            }
        }
        return num - ret;
    }
};
